
#!/bin/usr/env python

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import os
from flask_script import Manager, Server, Shell
from flask_migrate import Migrate, MigrateCommand

from app import create_app, db

config_name = os.environ.get('CONFIG_NAME', 'default')
app = create_app(config_name)    
manager = Manager(app)
migrate = Migrate(app, db)

@manager.command
def init_db():
    db.create_all()

def make_shell_context():
    return dict(app=app, db=db)

def main():
    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    manager.add_command("runserver",
                        Server(host=HOST, port=PORT, use_debugger=True))
    manager.add_command("shell", Shell(make_context=make_shell_context))
    manager.add_command("db", MigrateCommand)
    manager.run()

if __name__ == '__main__':
    main()